import axios from 'axios';
import {API_BASE_URL} from '@/common/config.js';
import { navigateToLogin } from '@/common/utils/utils.js';
import store from '@/store/index';


axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
	// axios中请求配置有baseURL选项，表示请求URL公共部分
	baseURL: API_BASE_URL,
	// 超时（毫秒）
	timeout: 600000
})
service.interceptors.request.use(
  config => {
    if (global.token) {
      config.headers['Authorization'] = global.token
    }
	config.headers['Content-Type'] = 'multipart/form-data'
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code != 9100) {
	  if (res.code == 9400) {
		  uni.showToast({
		      title: '登录失效，请重新登录',
		      icon: 'none',
		  })
		  store.commit("logout");
		  navigateToLogin();
	  } else {
		  uni.showToast({
		  	title: res.msg || 'Error',
			icon: 'none'
		  })
	  }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err:' + error) // for debug
    return Promise.reject(error)
  }
)

export default service;